using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace GP2D3D_Huiswerk2_RickBeijer_S1012261
{
    /// <summary>
    /// This is a game component that implements IUpdateable.
    /// </summary>
    public class PointList : Microsoft.Xna.Framework.DrawableGameComponent, IPointList
    {
        private Dictionary<Vector3, VertexPositionColor> points;
        private BasicEffect basicEffect;

        public PointList(Game game, BasicEffect basicEffect)
            : base(game)
        {
            this.points = new Dictionary<Vector3, VertexPositionColor>();
            this.basicEffect = basicEffect;
        }

        public void Add(Vector3 location, Color color)
        {
            if (!points.ContainsKey(location))
            {
                points.Add( location, new VertexPositionColor( location, color ) );
            }
            else
            {
                points[location] = new VertexPositionColor( location, color );
            }
        }

        public VertexPositionColor Remove(Vector3 location)
        {
            if (points.ContainsKey(location))
            {
                return points[location];
            }

            return new VertexPositionColor();
        }

        public override void Draw(GameTime gameTime)
        {
            if (points.Count > 0)
            {
                VertexPositionColor[] pointVertices = points.Values.ToArray();
                VertexBuffer pointBuffer = new VertexBuffer( GraphicsDevice,
                                                             pointVertices.Length * VertexPositionColor.SizeInBytes,
                                                             BufferUsage.None );
                pointBuffer.SetData<VertexPositionColor>( pointVertices );
                GraphicsDevice.VertexDeclaration = new VertexDeclaration( GraphicsDevice, VertexPositionColor.VertexElements );
                GraphicsDevice.Vertices[0].SetSource( pointBuffer, 0, VertexPositionColor.SizeInBytes );

                basicEffect.Begin();
                basicEffect.VertexColorEnabled = true;

                foreach ( EffectPass effectPass in basicEffect.CurrentTechnique.Passes )
                {
                    effectPass.Begin();
                    GraphicsDevice.DrawPrimitives( PrimitiveType.PointList, 0, pointVertices.Length );
                    effectPass.End();
                }

                basicEffect.End();
            }

            base.Draw(gameTime);
        }
    }
}